/*
 * Copyright (c) 2023-2023 elsfs Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.elsfs.cloud.spring.authorizationserver.oidc;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.OAuth2Error;
import org.springframework.security.oauth2.core.OAuth2ErrorCodes;
import org.springframework.security.oauth2.core.http.converter.OAuth2ErrorHttpMessageConverter;
import org.springframework.security.oauth2.core.oidc.OidcUserInfo;
import org.springframework.security.oauth2.server.authorization.oidc.authentication.OidcUserInfoAuthenticationToken;
import org.springframework.security.oauth2.server.authorization.oidc.http.converter.OidcUserInfoHttpMessageConverter;
import org.springframework.security.oauth2.server.authorization.oidc.web.OidcUserInfoEndpointFilter;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

/**
 * 用于处理 "已认证" 的 OidcUserInfoAuthenticationToken 并返回 UserInfo 响应
 * 设置用于处理OAuth2AuthenticationException并返回错误响应的AuthenticationFailureHandler。
 *
 * @author zeng
 * @see OidcUserInfoEndpointFilter#setAuthenticationSuccessHandler(AuthenticationSuccessHandler)
 * @see OidcUserInfoEndpointFilter#setAuthenticationFailureHandler(AuthenticationFailureHandler)
 */
public class UserInfoResponseHandler
    implements AuthenticationSuccessHandler, AuthenticationFailureHandler {
  private final HttpMessageConverter<OidcUserInfo> userInfoHttpMessageConverter =
      new OidcUserInfoHttpMessageConverter();
  private final HttpMessageConverter<OAuth2Error> errorHttpResponseConverter =
      new OAuth2ErrorHttpMessageConverter();

  /**
   * 成功处理器
   *
   * @param request the request which caused the successful authentication
   * @param response the response
   * @param authentication the <tt>Authentication</tt> object which was created during the
   *     authentication process.
   */
  @Override
  public void onAuthenticationSuccess(
      HttpServletRequest request, HttpServletResponse response, Authentication authentication)
      throws IOException {
    OidcUserInfoAuthenticationToken userInfoAuthenticationToken =
        (OidcUserInfoAuthenticationToken) authentication;
    ServletServerHttpResponse httpResponse = new ServletServerHttpResponse(response);
    this.userInfoHttpMessageConverter.write(
        userInfoAuthenticationToken.getUserInfo(), null, httpResponse);
  }

  /**
   * 失败处理器
   *
   * @param request the request during which the authentication attempt occurred.
   * @param response the response.
   * @param authenticationException the exception which was thrown to reject the authentication
   *     request.
   */
  @Override
  public void onAuthenticationFailure(
      HttpServletRequest request,
      HttpServletResponse response,
      AuthenticationException authenticationException)
      throws IOException {
    OAuth2Error error = ((OAuth2AuthenticationException) authenticationException).getError();
    HttpStatus httpStatus = HttpStatus.BAD_REQUEST;
    if (error.getErrorCode().equals(OAuth2ErrorCodes.INVALID_TOKEN)) {
      httpStatus = HttpStatus.UNAUTHORIZED;
    } else if (error.getErrorCode().equals(OAuth2ErrorCodes.INSUFFICIENT_SCOPE)) {
      httpStatus = HttpStatus.FORBIDDEN;
    }
    ServletServerHttpResponse httpResponse = new ServletServerHttpResponse(response);
    httpResponse.setStatusCode(httpStatus);
    this.errorHttpResponseConverter.write(error, null, httpResponse);
  }
}
